require 'rubygems'
require 'pp'
require 'activerecord'

config = YAML.load_file(File.join(File.dirname(__FILE__), 'database.yml'))
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => config[:development.to_s][:database.to_s])

class Instances < ActiveRecord::Base
end

class PrintFilter
    def process(line)
        pp line
    end
end

class EntryFilter
    def initialize(pattern)
        @pattern = %r{#{pattern}}
    end
    
    def process(line)
        line if line =~ @pattern
    end
end

class IgnoreFilter
    def initialize(*patterns)
        @patterns = patterns
    end
    
    def process(line)
        result = line
        @patterns.each do |p|
            result = nil if result =~ /#{p}/
        end
        return result
    end
end

class AddInstanceFilter
    def process(line)
        line =~ /\[((\d|\s|\:)*)\]\s\[(\w|\W)*\](\s)+INFO(\s)*(\w-(\d|\w)+)\sstate\schange:\s((\w)+)\s->\s((\w)+)/
        event_date = $1
        instance_id = $6
        from_state = $8
        to_state = $10
        
#        pp "Time: #{event_date}, Instance: #{instance_id}, From State: #{from_state}, To:#{to_state}"
        
        i = Instances.new
        i.instance_id = instance_id
        i.event_date = DateTime.parse(event_date)
        i.from_state = from_state
        i.to_state = to_state
        i.save
        line
    end
end

class LogParser
    def initialize(log_file)
        @log_file = log_file
        @filters = []
    end
    
    def <<(new_filter)
        @filters << new_filter
    end
    
    def process_log()
        line_count = 0
        IO.foreach(@log_file) do |line|
            line_count += 1
            result = line
            @filters.each do |filter|
                result = filter.process(result) if result # only pass result to the next filter if not nil(rejected by earlier filters)
            end
            
            #pp result if result
        end
    end
end

def parse_logfile(log_file)
    lp = LogParser.new(log_file)
    yield lp
    lp.process_log
end

#parse_logfile("cc_filter.log") do |parser|
#    parser << EntryFilter.new("EUCA[WARN|ERROR]")
#    parser << IgnoreFilter.new("failed to terminate", "TerminateInstance");
#    parser << PrintFilter.new()
#end

#parse_logfile("cloud-debug.log") do |parser|
#    parser << EntryFilter.new("state change")
#    parser << IgnoreFilter.new("RUNNING -> RUNNING", "PENDING -> PENDING")
#    parser << AddInstanceFilter.new
#    parser << PrintFilter.new
#end

#parse_logfile("cloud-debug.log") do |parser|
#    parser << EntryFilter.new("euca:")
#    parser << PrintFilter.new
#end
